package es

import (
	"fmt"
	"gin/app/http/global"
	"github.com/elastic/go-elasticsearch/v8"
	"github.com/spf13/viper"
	"log"
	"sync"
)

var (
	mu sync.Mutex
)

func InitEs() error {
	mu.Lock()
	defer mu.Unlock()
	// 创建Elasticsearch客户端
	Addresses := viper.GetString("es.addresses")
	cfg := elasticsearch.Config{
		Addresses: []string{
			Addresses, // Elasticsearch的地址
		},
	}
	client, err := elasticsearch.NewClient(cfg)
	if err != nil {
		fmt.Println("Elasticsearch连接不成功！")
		log.Fatalf("Error creating the Elasticsearch client: %s", err)
		return err
	}

	// 在此处执行一个测试操作，以确保客户端与服务器建立连接
	info, err := client.Info()
	if err != nil {
		fmt.Printf("无法与Elasticsearch建立连接: %s\n", err)
		return err
	}

	global.Es = client
	fmt.Println("Elasticsearch连接成功", "\n", info)
	return nil
}
